/***********************************************
This file is part of the AMonSys project (https://apms.cz.cc).

    AMonSys is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AMonSys is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AMonSys.  If not, see <http://www.gnu.org/licenses/>.
**********************************************/
package config

import(
	"time";
	"os";
	"math";
	"strings";
	"strconv";
	"io/ioutil";
	"fmt";
	"bytes";
)

type AstConfig struct {
	Pass	string;
	Port	string;
	Queue	string;
	Srv	string;
	User	string;
}

type ApmsConfig struct {
	ConfDir		string
	LogDir		string
	LangDir		string
	LangDefault	string
	HttpDir		string
	HttpIP		string
	HttpPort	string
	QueuePeer	string
	QueueShow	string
	LogFolder	string
}

func Sleep(t int64){
	c := make(chan int);
	wt := t*int64(math.Pow(10,8));
	go func(){
		time.Sleep(wt);
		c <- 1;
	}();
	<- c;
}

func Kill(){
	os.Exit(1);
}

func LoadConf(cfgDir string) (AstConfig, ApmsConfig){
	var(
	astcfg		AstConfig;
	apmsConf	ApmsConfig;
	)
	filename := strings.TrimRight(cfgDir,"/")+"/amonsys.conf";
	conf := make(map[string]string);
	body, err := ioutil.ReadFile(filename);
	if err != nil {
		errType := strings.Split(err.String(),":",-1);
		msg := strings.TrimRight(strings.TrimLeft(errType[1]," ")," ")
		fmt.Print("\x1b[31m"+"["+"\x1b[5m"+"Error"+"\x1b[0m"+"\x1b[31m"+"]"+"\x1b[31m "+msg+": "+"\x1b[0m"+"\x1b[34m"+filename+"\x1b[0m"+"\n");
		os.Exit(1);
	}
	nbody := bytes.Split(body,[]byte("\n"),-1);
	for i:=0; i<len(nbody); i++{
		data := strings.Split(string(nbody[i]),"#",-1);
		if data[0] != "" {
			line := strings.Split(data[0],"=",-1);
			if len(line) > 1 {
				conf[strings.TrimSpace(string(line[0]))] = strings.TrimLeft(strings.TrimRight(string(line[1]),"\""),"\""),true;
			}
		}
	}

	for key,value := range conf {
		switch key {
			case "astman_server":
				astcfg.Srv = value;
			case "astman_port":
				astcfg.Port = value;
			case "astman_user":
				astcfg.User = value;
			case "astman_pass":
				astcfg.Pass = value;
			case "astman_queue":
				astcfg.Queue = value;
			case "astman_queueowner":
				apmsConf.QueuePeer = value;
			case "astman_queueshow":
				apmsConf.QueueShow = value;
			case "http_folder":
				apmsConf.HttpDir = strings.TrimRight(value,"/");
			case "http_broadcast_ip":
				apmsConf.HttpIP = value;
			case "http_port":
				apmsConf.HttpPort = value;
			case "lang_folder":
				apmsConf.LangDir = strings.TrimRight(value,"/");
			case "lang_default":
				apmsConf.LangDefault = value;
			case "log_folder":
				apmsConf.LogFolder = value;
		}
	}
return astcfg, apmsConf;
}

func SetLanguage(l string,conf ApmsConfig) map[string]string {
	lang := make(map[string]string);
	filename := strings.TrimRight(conf.LangDir,"/")+"/"+l;
	body, err1 := ioutil.ReadFile(filename);
	if err1 != nil {
		filename := strings.TrimRight(conf.LangDir,"/")+"/"+conf.LangDefault;
		body, err2 := ioutil.ReadFile(filename);
		if err2 != nil {
			error := LogError(err2.String(),conf.LogFolder)
			fmt.Print(error)
		}
		nbody := bytes.Split(body,[]byte("\n"),-1);
		for i:=0; i<len(nbody); i++{
			data := bytes.Split(nbody[i],[]byte("="),-1);
			lang[strings.TrimSpace(string(data[0]))] = strings.TrimLeft(strings.TrimRight(string(data[1]),"\""),"\""),true;
		}
	} else {
		nbody := bytes.Split(body,[]byte("\n"),-1);
		for i:=0; i<len(nbody); i++{
			data := bytes.Split(nbody[i],[]byte("="),-1);
			lang[strings.TrimSpace(string(data[0]))] = strings.TrimLeft(strings.TrimRight(string(data[1]),"\""),"\""),true;
		}
	}
	return lang;
}

func ValorToTime(t string) string {
	var tf string;
	time := strings.Split(t,":",-1);
	if time[0] != "00" {
		if time[0][0:1] !="0"{
			tf = time[0]+":";
		} else {
			tf = time[0][1:]+":";
		}
	}
	tf = tf+time[1]+":"+time[2];
	return tf;
}

func SecondsToTime(sec int64) string {
	var( seg,min,hr string );
	tempo := time.SecondsToUTC(sec);
	if strings.TrimSpace(strconv.Itoa(tempo.Hour)) != "0" {
		hr = "0"+strings.TrimSpace(strconv.Itoa(tempo.Hour))+":";
	}
	if len(strings.TrimSpace(strconv.Itoa(tempo.Minute))) < 2{
		min = "0"+strings.TrimSpace(strconv.Itoa(tempo.Minute));
	} else {
		min = strings.TrimSpace(strconv.Itoa(tempo.Minute));
	}
	if len(strings.TrimSpace(strconv.Itoa(tempo.Second))) < 2{
		seg = "0"+strings.TrimSpace(strconv.Itoa(tempo.Second));
	} else {
		seg = strings.TrimSpace(strconv.Itoa(tempo.Second));
	}
	return hr+min+":"+seg;
}

func LogError(err string,folder string) string {
	filename := strings.TrimRight(folder,"/")+"/error.log"
	msg := "["+LogDT()+"] "+err+"\n"
	body, error := ioutil.ReadFile(filename)
	if error == nil {
		newError := bytes.Add(body,[]byte(msg))
		_ = ioutil.WriteFile(filename,newError,0644)
	} else {
		newError := []byte(msg)
		_ = ioutil.WriteFile(filename,newError,0644)
	}
	return msg
}

func LogConnection(err string,folder string) string {
	filename := strings.TrimRight(folder,"/")+"/access.log"
	msg := "["+LogDT()+"] "+err+"\n"
	body, error := ioutil.ReadFile(filename)
	if error == nil {
		newError := bytes.Add(body,[]byte(msg))
		_ = ioutil.WriteFile(filename,newError,0644)
	} else {
		newError := []byte(msg)
		_ = ioutil.WriteFile(filename,newError,0644)
	}
	return msg
}

func LogAsterisk(err string,folder string) string {
	filename := strings.TrimRight(folder,"/")+"/asterisk.log"
	msg := "["+LogDT()+"] "+err+"\n"
	body, error := ioutil.ReadFile(filename)
	if error == nil {
		newError := bytes.Add(body,[]byte(msg))
		_ = ioutil.WriteFile(filename,newError,0644)
	} else {
		newError := []byte(msg)
		_ = ioutil.WriteFile(filename,newError,0644)
	}
	return msg
}

func LogDT() string {
	var day,month,year,hr,mn,sc string
	tempo := time.LocalTime()
	if len(strconv.Itoa(tempo.Day))<2 {day = "0"+strconv.Itoa(tempo.Day)} else {day = strconv.Itoa(tempo.Day)}
	if len(strconv.Itoa(tempo.Month))<2 {month = "0"+strconv.Itoa(tempo.Month)} else {month = strconv.Itoa(tempo.Month)}
	year = strconv.Itoa64(tempo.Year)
	if len(strconv.Itoa(tempo.Hour))<2 {hr = "0"+strconv.Itoa(tempo.Hour)} else {hr = strconv.Itoa(tempo.Hour)}
	if len(strconv.Itoa(tempo.Minute))<2 {mn = "0"+strconv.Itoa(tempo.Minute)} else {mn = strconv.Itoa(tempo.Minute)}
	if len(strconv.Itoa(tempo.Second))<2 {sc = "0"+strconv.Itoa(tempo.Second)} else {sc = strconv.Itoa(tempo.Second)}
	final := day+"/"+month+"/"+year+" - "+strings.TrimSpace(hr+":"+mn+":"+sc)
	return final
}
